package com.example.admin.service.imp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.admin.Dto.HuaweiAuthDto;
import com.example.admin.bean.Device;
import com.example.admin.bean.DeviceData;
import com.example.admin.bean.Devicedto;
import com.example.admin.mapper.Iotmapper;
import com.example.admin.mqtt.RawMessage;
import com.example.admin.service.Lotservice;
import com.example.admin.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ImpLotservice implements Lotservice {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    Iotmapper iotmapper;
    @Override
    public void adddevice(Device device) {

        String token = redisTemplate.opsForValue().get("huaweiyun:auth:token");
        if (StringUtils.isEmpty(token)){
            token =  auth();
        }
        StringBuffer url =
                new StringBuffer("https://6cb358bfc7.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/574b551ae0064ae5a120a46b253d46e4/devices");
        HttpHeaders header = new HttpHeaders();
        header.add("X-Auth-Token",token);
        header.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(device,header);
        String nodeid = UUID.randomUUID().toString();
        device.setNode_id(nodeid);
        ResponseEntity<String> response = restTemplate.exchange(url.toString(), HttpMethod.POST, entity, String.class);
        String body = response.getBody();
        JSONObject object = JSONObject.parseObject(body);
        System.out.println(object.toString());
        device.setDevice_id(object.getString("device_id"));
        device.setProductName(object.getString("product_name"));
        iotmapper.adddevice(device);
        System.out.println("保存数据库成功");


    }

    @Override
    public Object searchdevice(String device_id) {
        String token = redisTemplate.opsForValue().get("huaweiyun:auth:token");
        if (StringUtils.isEmpty(token)){
            token =  auth();
        }
        StringBuffer url =
                new StringBuffer("https://6cb358bfc7.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/574b551ae0064ae5a120a46b253d46e4/devices"+"/"+device_id);
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Auth-Token",token);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(headers);
        ResponseEntity<String> resp = restTemplate.exchange(url.toString(), HttpMethod.GET, entity, String.class);
        String message = resp.getBody();
        System.out.println(message);
        Object parse = JSONObject.parse(message);
        return parse;
    }

    @Override
    public Object whatchobjectmodel(String product_id) {
        String token = redisTemplate.opsForValue().get("huaweiyun:auth:token");
        if (StringUtils.isEmpty(token)){
            token =  auth();
        }
        StringBuffer url =
                new StringBuffer("https://6cb358bfc7.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/574b551ae0064ae5a120a46b253d46e4/products"+"/"+product_id);
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Auth-Token",token);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(headers);
        ResponseEntity<String> resp = restTemplate.exchange(url.toString(), HttpMethod.GET, entity, String.class);
        System.out.println(resp.getBody());
        Object result = JSONObject.parse(resp.getBody());
        return result;
    }

    @Override
    public void fixdevice(Device device) {
        String token = redisTemplate.opsForValue().get("huaweiyun:auth:token");
        if (StringUtils.isEmpty(token)){
            token =  auth();
        }
        StringBuffer url =
                new StringBuffer("https://6cb358bfc7.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/574b551ae0064ae5a120a46b253d46e4/devices"+"/"+device.getDevice_id());
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Auth-Token",token);
        headers.setContentType(MediaType.APPLICATION_JSON);
        Map<String, Object> requestBody = new HashMap<>();
        HttpEntity<Object> entity = new HttpEntity<>(requestBody,headers);
        try {
            ResponseEntity<String> resp = restTemplate.exchange(url.toString(), HttpMethod.PUT, entity, String.class);
        } catch (RestClientException e) {
            throw new RuntimeException(e);
        }

        iotmapper.fixdevice(device);
    }

    @Override
    public void deletedevice(String device_id) {
        String token = redisTemplate.opsForValue().get("huaweiyun:auth:token");
        if (StringUtils.isEmpty(token)){
            token =  auth();
        }
        StringBuffer url =
                new StringBuffer("https://6cb358bfc7.st1.iotda-app.cn-north-4.myhuaweicloud.com:443/v5/iot/574b551ae0064ae5a120a46b253d46e4/devices"+"/"+device_id);
        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Auth-Token",token);
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(headers);
        ResponseEntity<String> resp = restTemplate.exchange(url.toString(), HttpMethod.DELETE, entity, String.class);
        if (resp.getStatusCodeValue() == 204){
            iotmapper.deletedevice(device_id);
        }else {
            throw new RuntimeException("删除设备失败");
        }
    }


    public String auth(){
        HuaweiAuthDto huaweiAuthDto = new HuaweiAuthDto();
        ResponseEntity<String> response = restTemplate.postForEntity("https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens", huaweiAuthDto, String.class);
        List<String> strings = response.getHeaders().get("X-Subject-Token");
        String token = strings.get(0);
        redisTemplate.opsForValue().set("huaweiyun:auth:token",token,23, TimeUnit.HOURS);
        return token;
    }

    public void printmessage(RawMessage message){
        System.err.println("接收到了物联网平台的在线消息"+"---------------------"+ LocalTime.now());
        System.out.println(message.getTopic().toString());
        System.out.println(new String(message.getPayload()));
        String payload = new String(message.getPayload());
        JSONObject json = JSONObject.parseObject(payload);
//        拿到produceid去数据库查询对应的设备
        JSONObject notifyData = json.getJSONObject("notify_data");
        JSONObject header = notifyData.getJSONObject("header");
        String deviceId = header.getString("device_id");
        Devicedto device = iotmapper.finddevicebyid(deviceId);
        //找到需要上报的属性
        JSONObject body = notifyData.getJSONObject("body");
        JSONArray services = body.getJSONArray("services");
        for (Object service : services) {
            JSONObject realservice = (JSONObject) service;
            JSONObject properties = realservice.getJSONObject("properties");
            Set<String> keys = properties.keySet();
            for (String key : keys) {
                String value = properties.getString(key);
                //将每个上报的属性成单行数据上传到数据库
                DeviceData deviceData = new DeviceData();
                deviceData.setDeviceName(device.getDeviceName());
                deviceData.setIotId(deviceId);
                deviceData.setNoteName(device.getNoteName());
                deviceData.setProductId(device.getProductId());
                deviceData.setProductName(device.getProductName());
                deviceData.setFunctionName(key);
                deviceData.setAccessLocation(device.getRemark());
                deviceData.setDataValue(value);
                String jsondata = JSONObject.toJSONString(deviceData);
                redisTemplate.opsForValue().set("redis:bed:data",jsondata,1,TimeUnit.DAYS);
                iotmapper.adddevicedata(deviceData);
            }
        }
    }

    @Override
    public DeviceData finddatabyid(String deviceId) {
      return   iotmapper.finddatabyid(deviceId);
    }
}
